package com.example.day03.lianxi.wordtext;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 流处理
 */
public class Demo2 {

    public static void main(String[] args) throws Exception {
        int defaultLocalParallelism = StreamExecutionEnvironment.getDefaultLocalParallelism();
        System.out.println(defaultLocalParallelism);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> stringDataStreamSource = env.readTextFile("E:\\note\\flink-project\\flink-leaning\\day04\\input\\word.txt");


        SingleOutputStreamOperator<Tuple2<String, Integer>>  wordCounts = stringDataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] split = s.split(" ");
                for (String string : split) {
                    Tuple2<String, Integer> stringIntegerTuple2 = Tuple2.of(string, 1);
                    out.collect(stringIntegerTuple2);
                }
            }
        });
        wordCounts.keyBy(value -> value.f0).sum(1).print();

        // 执行 Flink 作业
        env.execute("Word Count Example");
    }
}
